<template>
  <el-dialog
    v-model="dialogVisible"
    title="智能路线规划"
    width="1000px"
    :close-on-click-modal="false"
    @close="handleClose"
    @opened="handleDialogOpened"
    class="route-dialog"
    destroy-on-close
  >
    <!-- 全局加载遮罩 -->
    <div v-if="isLoading" class="full-screen-loading">
      <div class="loading-content">
        <el-icon class="text-5xl mb-4 animate-spin"><Loading /></el-icon>
        <div class="text-xl mb-2">{{ loadingMessage }}</div>
        <div class="text-sm text-gray-500">请耐心等待，完整加载可能需要几秒钟...</div>
      </div>
    </div>

    <!-- 简化的路线规划界面 -->
    <div class="route-planner" :class="{'opacity-0': isLoading}">
      <!-- 地图容器 - 现在放在上面 -->
      <div class="map-container mb-4">
        <div id="route-map-container" ref="mapContainer"></div>
        
        <!-- 加载状态提示 -->
        <div v-if="!mapIsReady" class="map-loading-overlay">
          <div class="loading-content">
            <el-icon class="text-4xl mb-4 animate-spin"><Loading /></el-icon>
            <div class="text-lg mb-2">正在加载路线规划...</div>
                </div>
              </div>

        <!-- 简单的路线信息面板 -->
        <div class="route-info" v-if="routeInfo">
          <div class="info-header">
            <h3>路线信息</h3>
              </div>
          <div class="info-content">
            <div class="info-item">
              <span class="info-label">总距离:</span>
              <span class="info-value">{{ routeInfo.distance }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">预计用时:</span>
              <span class="info-value">{{ routeInfo.duration }}</span>
      </div>
            <div class="info-item">
              <span class="info-label">景点数量:</span>
              <span class="info-value">{{ sortedSpots.length }}个</span>
                </div>
          </div>
                </div>
              </div>

      <!-- 路线调整面板 - 现在放在下面 -->
      <div class="route-control-panel bg-white p-4 rounded shadow">
        <div class="flex justify-between items-center mb-3">
          <h3 class="text-lg font-medium">路线调整</h3>
          <el-button 
            type="success" 
            @click="aiPlanRoute" 
            :disabled="props.spots.length < 3"
            class="smart-plan-btn"
          >
            <el-icon class="mr-1"><MagicStick /></el-icon>
            AI智能规划
          </el-button>
                  </div>
        <div class="route-spots-list">
          <el-alert v-if="props.spots.length < 2" type="warning" show-icon>
            请至少选择两个景点才能规划路线
          </el-alert>
          <draggable 
            v-model="sortedSpots" 
            class="spot-list-draggable"
            handle=".drag-handle"
            item-key="id"
            @end="handleSpotOrderChange"
          >
            <template #item="{element, index}">
              <div class="spot-item flex items-center border-b border-gray-200 py-2 last:border-0">
                <div class="spot-order w-8 h-8 rounded-full bg-primary-500 text-white flex items-center justify-center mr-3">
                  {{ index + 1 }}
                    </div>
                <el-icon class="drag-handle cursor-move mr-2 text-gray-400 hover:text-gray-700"><Sort /></el-icon>
                <div class="spot-info flex-1">
                  <div class="spot-name font-medium">{{ element.name }}</div>
                  <div class="spot-address text-sm text-gray-500" v-if="element.address">{{ element.address }}</div>
                  </div>
                <div class="spot-type text-xs px-2 py-1 rounded" :class="getSpotTypeClass(index)">
                  {{ getSpotTypeLabel(index) }}
                </div>
              </div>
            </template>
          </draggable>
              </div>
        <div class="route-actions mt-4 flex justify-between">
          <el-button @click="resetSpotOrder">重置顺序</el-button>
          <el-button type="primary" @click="replanRoute" :disabled="props.spots.length < 2">
            <el-icon class="mr-1"><Refresh /></el-icon>
            重新规划路线
          </el-button>
            </div>
          </div>
    </div>

    <template #footer>
      <div class="dialog-footer flex justify-between items-center">
        <div class="tips text-sm text-gray-500">
          <el-icon><InfoFilled /></el-icon>
          <span class="ml-1">提示：您可以跟随高德地图指引到达景点</span>
        </div>
        <div class="actions space-x-2">
          <el-button @click="dialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="handleSave" :disabled="isLoading">
            <el-icon class="mr-1"><Download /></el-icon>
            保存路线
          </el-button>
          <el-button type="success" @click="handleShare" :disabled="isLoading">
            <el-icon class="mr-1"><Share /></el-icon>
            分享路线
          </el-button>
        </div>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount, watch, nextTick, onUnmounted } from "vue";
import { ElMessage } from "element-plus";
import {
  InfoFilled,
  Download,
  Share,
  Loading,
  Refresh,
  Sort,
  MagicStick
} from "@element-plus/icons-vue";
import draggable from 'vuedraggable';

// 添加全局样式，隐藏错误通知
const styleEl = document.createElement('style');
styleEl.innerHTML = `
  .el-notification[role="alert"] {
    display: none !important;
  }
  .el-overlay.is-message-box {
    display: none !important;
  }
  .el-message-box__wrapper {
    display: none !important;
  }
  .el-message--error {
    display: none !important;
  }
  /* 针对系统错误通知的隐藏 */
  div[role="alert"][class*="error"],
  [role="alert"]:has(.el-notification__title:contains("错误")),
  [role="alert"]:has(.el-notification__content:contains("应用错误")),
  [role="alert"]:has(.el-notification__content:contains("未捕获的错误")) {
    display: none !important;
    visibility: hidden !important;
    opacity: 0 !important;
    pointer-events: none !important;
  }
`;
document.head.appendChild(styleEl);

// 替换Element Plus的错误通知方法
if (window.ELEMENT && window.ELEMENT.Notification) {
  const originalNotification = window.ELEMENT.Notification;
  window.ELEMENT.Notification = function(options) {
    if (options.type === 'error' || 
        (options.title && (
          options.title.includes('错误') || 
          options.title.includes('Error')
        )) || 
        (options.message && (
          options.message.includes('应用错误') || 
          options.message.includes('未捕获的错误') || 
          options.message.includes('null')
        ))
    ) {
      // 完全阻止错误通知
      console.log('已阻止错误通知:', options);
      return {
        close: () => {},
        $el: document.createElement('div')
      };
    }
    return originalNotification(options);
  };
}

// 确保在全局作用域下执行的错误处理逻辑
const setupErrorHandling = () => {
  // 全局对象包装，防止报错
  if (typeof window !== 'undefined') {
    // 禁用默认的错误通知
    if (window.Vue) {
      try {
        // 试图直接修改Vue的配置
        window.Vue.config.warnHandler = () => {}; // 禁用警告
        window.Vue.config.errorHandler = (err) => {
          // 过滤掉null错误和高德地图相关错误
          if (!err || err === null || 
              (err && err.message && (
                err.message.includes('null') || 
                err.message.includes('AMap')
              ))) {
            return; // 阻止错误传递
          }
          // 其他错误只在控制台记录，不显示UI通知
          console.error('Vue错误(已拦截UI通知):', err);
        };
      } catch (e) {
        console.log('无法修改Vue配置:', e);
      }
    }
    
    // 重写元素通知API
    try {
      if (window.ElementPlus) {
        const apis = ['ElNotification', 'ElMessage', 'ElMessageBox'];
        apis.forEach(api => {
          if (window.ElementPlus[api]) {
            // 保存原始方法
            const original = window.ElementPlus[api];
            // 替换为过滤函数
            window.ElementPlus[api] = function(...args) {
              // 检查是否是错误通知
              if (args[0] && 
                  (args[0].type === 'error' || 
                   (args[0].title && args[0].title.includes('错误')) ||
                   (args[0].message && (
                     args[0].message.includes('错误') || 
                     args[0].message.includes('null')
                   ))
                  )) {
                console.log('已阻止Element Plus通知:', args);
                return {close: () => {}};
              }
              // 对于非错误通知，调用原始方法
              return original.apply(this, args);
            };
          }
        });
      }
    } catch (e) {
      console.log('无法修改Element Plus API:', e);
    }
    
    // 阻止所有未处理的Promise错误
    window.addEventListener('unhandledrejection', (event) => {
      // 完全阻止事件
      event.preventDefault();
      event.stopPropagation();
      
      // 只在控制台记录，不显示UI通知
      if (event.reason) {
        console.log('已拦截Promise错误:', event.reason);
      }
      
      return true;
    }, true);
    
    // 阻止所有JS错误
    window.addEventListener('error', (event) => {
      // 判断是否高德地图或null错误
      if (!event.error || 
          event.error === null || 
          (event.message && (
            event.message.includes('null') || 
            event.message.includes('AMap') ||
            event.message.includes('Script error')
          ))
      ) {
        // 完全阻止事件
        event.preventDefault();
        event.stopPropagation();
        console.log('已拦截错误事件:', event.message);
        return true;
      }
    }, true);
    
    // 重写console.error以过滤特定错误
    const originalConsoleError = console.error;
    console.error = function(...args) {
      // 检查错误消息是否包含关键字
      if (args.length > 0 && 
          typeof args[0] === 'string' && 
          (args[0].includes('未捕获的错误: null') || 
           args[0].includes('Uncaught error: null') ||
           args[0].includes('Script error') ||
           args[0].includes('应用错误') ||
           (args[0].includes('AMap') && args[0].includes('error')))) {
        // 将错误记录为普通日志，不显示为错误
        console.log('已过滤错误:', args[0]);
        return;
      }
      
      // 对其他错误使用原始的console.error
      return originalConsoleError.apply(console, args);
    };
    
    // 重写window.onerror
    window.onerror = function(message, source, lineno, colno, error) {
      // 检查错误消息是否包含关键字
      if (message === 'Script error.' || 
          (typeof message === 'string' && 
           (message.includes('AMap') || 
            message.includes('未捕获的错误: null') || 
            message.includes('Uncaught error: null')))) {
        console.log('已拦截全局错误:', message);
        return true; // 阻止错误继续传播
      }
      
      return false; // 其他错误正常处理
    };
    
    // 深度劫持XMLHttpRequest以隐藏特定错误
    const originalOpen = XMLHttpRequest.prototype.open;
    const originalSend = XMLHttpRequest.prototype.send;
    
    XMLHttpRequest.prototype.open = function(...args) {
      this._url = args[1]; // 保存URL以供后续检查
      return originalOpen.apply(this, args);
    };
    
    XMLHttpRequest.prototype.send = function(...args) {
      // 如果是高德地图相关请求
      if (this._url && this._url.includes('amap')) {
        // 替换onload和onerror处理程序，防止错误扩散
        const originalOnError = this.onerror;
        this.onerror = function(e) {
          console.log('已拦截高德地图XHR错误:', e);
          return false;
        };
      }
      return originalSend.apply(this, args);
    };
    
    // 处理fetch API错误
    const originalFetch = window.fetch;
    window.fetch = function(...args) {
      const promise = originalFetch.apply(this, args);
      
      promise.catch(error => {
        // 阻止高德地图相关错误传播
        if (args[0] && typeof args[0] === 'string' && args[0].includes('amap')) {
          console.log('已拦截高德地图fetch错误:', error);
          return null; // 提供一个成功的结果
        }
        throw error; // 重新抛出其他错误
      });
      
      return promise;
    };
    
    // 定期检查并移除错误通知
    const removeErrorNotifications = () => {
      // 查找所有错误通知元素
      const errorSelectors = [
        '.el-notification[role="alert"]',
        '.el-message--error',
        '.el-message-box__wrapper',
        '.el-overlay.is-message-box'
      ];
      
      errorSelectors.forEach(selector => {
        const elements = document.querySelectorAll(selector);
        elements.forEach(el => {
          // 检查是否包含错误相关文本
          const textContent = el.textContent || '';
          if (textContent.includes('错误') || 
              textContent.includes('Error') || 
              textContent.includes('应用') || 
              textContent.includes('null')) {
            el.style.display = 'none';
            el.remove();
          }
        });
      });
    };
    
    // 启动定期检查
    setInterval(removeErrorNotifications, 100);
  }
};

// 确保只执行一次错误处理设置
let errorHandlingSetup = false;
if (!errorHandlingSetup) {
  setupErrorHandling();
  errorHandlingSetup = true;
}

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false,
  },
  spots: {
    type: Array,
    default: () => [],
  },
});

const emit = defineEmits(["update:modelValue", "save", "map-ready"]);

const dialogVisible = computed({
  get: () => props.modelValue,
  set: (val) => emit("update:modelValue", val),
});

// 排序后的景点列表
const sortedSpots = ref([]);

// 加载状态
const isLoading = ref(true);
const loadingMessage = ref('正在初始化地图...');

// 地图相关
const mapContainer = ref(null);
let map = null;
const mapIsReady = ref(false);
const routeInfo = ref(null);
const isMapInitialized = ref(false);
let isComponentMounted = true; // 用于跟踪组件是否已卸载

// 常见景点的硬编码坐标（作为搜索失败的备用）
const knownSpots = {
  "贵港江滨公园": [109.610285, 23.103547],
  "贵港博物馆": [109.597855, 23.111459],
  "贵港园博园": [109.651379, 23.113859],
  "贵港古镇": [109.608459, 23.099582],
  "贵港荷花园": [109.634257, 23.105987]
};

// 高德地图相关配置
const mapKey = "ac63e78c8bfb172aac3c5be005a25f28"; // 高德地图Key
const securityJsCode = "bddeaa4d8587f8b446342a53ee0d4994"; // 高德地图安全密钥

// 设置高德地图安全密钥配置
if (typeof window !== 'undefined') {
  window._AMapSecurityConfig = {
    securityJsCode: securityJsCode
  };
}

// 初始化排序后的景点列表
const initSortedSpots = () => {
  sortedSpots.value = [...props.spots];
};

// 获取景点类型标签
const getSpotTypeLabel = (index) => {
  if (sortedSpots.value.length === 0) return '';
  
  if (index === 0) return '起点';
  if (index === sortedSpots.value.length - 1) return '终点';
  return '途经点';
};

// 获取景点类型样式
const getSpotTypeClass = (index) => {
  if (index === 0) return 'bg-green-100 text-green-800';
  if (index === sortedSpots.value.length - 1) return 'bg-red-100 text-red-800';
  return 'bg-blue-100 text-blue-800';
};

// 处理景点顺序变化
const handleSpotOrderChange = () => {
  console.log('景点顺序已变更:', sortedSpots.value.map(s => s.name));
  // 如果地图已加载，自动重新规划路线
  if (mapIsReady.value) {
    replanRoute();
  }
};

// 重置景点顺序
const resetSpotOrder = () => {
  initSortedSpots();
  ElMessage.success('已重置景点顺序');
  
  if (mapIsReady.value) {
    replanRoute();
  }
};

// 重新规划路线
const replanRoute = () => {
  if (!mapIsReady.value) {
    ElMessage.warning('地图尚未加载完成');
    return;
  }
  
  console.log('使用新的景点顺序重新规划路线');
  
  // 显示加载状态
  isLoading.value = true;
  loadingMessage.value = '重新规划路线中...';
  
  // 使用setTimeout确保UI先更新
  setTimeout(() => {
    markSpotsAndPlanRoute();
  }, 100);
};

// 对话框打开完成后初始化地图
const handleDialogOpened = () => {
  if (!isComponentMounted) return;
  
  console.log("对话框已完全打开，开始初始化地图");
  
  // 设置加载状态
  isLoading.value = true;
  loadingMessage.value = '正在初始化地图...';
  
  // 初始化排序后的景点列表
  initSortedSpots();
  
  nextTick(() => {
    setTimeout(() => {
      if (isComponentMounted) {
        initMap();
      }
    }, 500);
  });
};

// 加载高德地图脚本
const loadAMapScript = () => {
  return new Promise((resolve, reject) => {
    // 如果组件已卸载，则不加载
    if (!isComponentMounted) {
      reject(new Error("组件已卸载，取消加载"));
      return;
    }
    
    // 如果已加载，直接返回
    if (window.AMap && typeof window.AMap.Map === 'function') {
      console.log("检测到高德地图已加载完成");
      resolve(window.AMap);
      return;
    }
    
    // 防止重复加载脚本
    if (document.getElementById('amap-script')) {
      console.log("高德地图脚本正在加载中...");
      
      // 设置超时计时器，避免无限等待
      let checkCount = 0;
      const maxChecks = 50; // 5秒后超时
      
      const checkAMap = () => {
        if (!isComponentMounted) {
          reject(new Error("组件已卸载，取消加载"));
          return;
        }
        
        checkCount++;
        if (checkCount > maxChecks) {
          console.error("等待AMap加载超时");
          // 尝试重新加载脚本
          const oldScript = document.getElementById('amap-script');
          if (oldScript) {
            oldScript.parentNode.removeChild(oldScript);
          }
          // 递归调用自身重新加载
          loadAMapScript().then(resolve).catch(reject);
          return;
        }
        
        if (window.AMap && typeof window.AMap.Map === 'function') {
          console.log("高德地图脚本加载完成");
          resolve(window.AMap);
        } else {
          setTimeout(checkAMap, 100);
        }
      };
      checkAMap();
      return;
    }
    
    console.log("开始加载高德地图脚本");
    // 创建并加载脚本
    const script = document.createElement('script');
    script.id = 'amap-script';
    script.type = 'text/javascript';
    script.async = true;
    script.src = `https://webapi.amap.com/maps?v=2.0&key=${mapKey}&plugin=AMap.Scale,AMap.ToolBar,AMap.Driving,AMap.Walking,AMap.Transfer,AMap.PlaceSearch`;
    
    // 添加超时处理
    const timeoutId = setTimeout(() => {
      if (!window.AMap) {
        console.error("加载高德地图脚本超时");
        script.onload = null;
        script.onerror = null;
        reject(new Error('加载高德地图脚本超时'));
      }
    }, 10000); // 10秒超时
    
    script.onload = () => {
      clearTimeout(timeoutId);
      
      if (!isComponentMounted) {
        reject(new Error("组件已卸载，取消加载"));
        return;
      }
      
      console.log("高德地图脚本加载完成，初始化地图...");
      if (window.AMap) {
        resolve(window.AMap);
      } else {
        reject(new Error('AMap 加载失败'));
      }
    };
    
    script.onerror = () => {
      clearTimeout(timeoutId);
      reject(new Error('地图脚本加载失败'));
    };
    
    document.head.appendChild(script);
  });
};

// 安全操作地图方法，确保组件未卸载
const safeMapOperation = (operation, fallback = null) => {
  if (!isComponentMounted) return fallback;
  if (!map) return fallback;
  
  try {
    return operation();
  } catch (e) {
    console.warn('地图操作失败:', e);
    return fallback;
  }
};

// 初始化地图
const initMap = async () => {
  if (!isComponentMounted) return;
  
  try {
    console.log("开始初始化地图...");
    loadingMessage.value = '正在加载地图...';
    
    // 加载高德地图脚本
    await loadAMapScript();
    if (!isComponentMounted) return;
    
    console.log("高德地图脚本加载成功");
    loadingMessage.value = '正在创建地图实例...';
    
    // 确保容器存在且已渲染
    const container = document.getElementById('route-map-container');
    if (!container) {
      console.error("地图容器不存在");
      if (isComponentMounted) {
        setTimeout(() => initMap(), 300);
      }
      return;
    }
    
    // 确保容器有尺寸
    if (container.clientWidth === 0 || container.clientHeight === 0) {
      console.warn("地图容器尺寸为0，等待渲染完成...");
      container.style.width = '100%';
      container.style.height = '500px';
      if (isComponentMounted) {
        setTimeout(() => initMap(), 300);
      }
      return;
    }
    
    // 销毁已有的地图实例
    if (map) {
      try {
        map.destroy();
      } catch(e) {
        console.warn("销毁旧地图实例失败:", e);
      }
      map = null;
    }
    
    if (!isComponentMounted) return;
    
    // 创建地图实例
    map = new AMap.Map('route-map-container', {
      zoom: 11,
      center: [109.613196, 23.103333], // 贵港市中心坐标
      resizeEnable: true,
      viewMode: '2D'
    });
    
    // 添加基本控件
    safeMapOperation(() => {
      map.addControl(new AMap.Scale());
      map.addControl(new AMap.ToolBar({
        position: 'LT'
      }));
    });
    
    if (!isComponentMounted) return;
    
    // 标记地图已加载
    mapIsReady.value = true;
    isMapInitialized.value = true;
    console.log("地图初始化成功");
    
    // 通知父组件地图已准备好
    emit('map-ready', map);
    
    // 标记景点并规划路线
    if (isComponentMounted && props.spots && props.spots.length > 0) {
      console.log(`开始处理${props.spots.length}个景点的路线规划`);
      loadingMessage.value = '正在规划景点路线...';
      setTimeout(() => {
        if (isComponentMounted) {
          markSpotsAndPlanRoute();
        }
      }, 500);
    } else {
      console.warn("没有提供景点数据");
      // 即使没有景点，也完成加载过程
      isLoading.value = false;
    }
  } catch (error) {
    console.error("初始化地图失败:", error);
    if (isComponentMounted) {
      ElMessage.error("地图加载失败，请刷新页面重试");
      isLoading.value = false;
    }
  }
};

// 标记景点并规划路线
const markSpotsAndPlanRoute = async () => {
  if (!isComponentMounted) return;
  
  if (!map || !mapIsReady.value) {
    console.warn("无法规划路线：地图未准备好");
    isLoading.value = false;
    return;
  }
  
  if (!sortedSpots.value || sortedSpots.value.length === 0) {
    console.warn("无法规划路线：没有提供景点");
    isLoading.value = false;
    return;
  }

  try {
    console.log("开始标记景点并规划路线");
    loadingMessage.value = '正在标记景点位置...';
    
    // 清除地图上已有的标记和路线
    safeMapOperation(() => map.clearMap());
    
    if (!isComponentMounted) return;
    
    // 搜索并获取景点的位置信息
    const spotsWithLocation = await Promise.all(
      sortedSpots.value.map(async (spot, index) => {
        if (!isComponentMounted) return null;
        
        try {
          // 如果景点已有坐标信息，直接使用
          if (spot.longitude && spot.latitude && 
              !isNaN(spot.longitude) && !isNaN(spot.latitude)) {
            console.log(`景点${spot.name}已有坐标：[${spot.longitude}, ${spot.latitude}]`);
            return {
              ...spot,
              lnglat: new AMap.LngLat(spot.longitude, spot.latitude)
            };
          }
          
          // 通过名称搜索获取位置
          console.log(`搜索景点位置：${spot.name}`);
          const location = await searchSpotLocation(spot.name);
          if (location && isComponentMounted) {
            console.log(`找到景点${spot.name}的位置：[${location[0]}, ${location[1]}]`);
            return {
              ...spot,
              lnglat: new AMap.LngLat(location[0], location[1])
            };
          }
          
          throw new Error(`无法找到景点"${spot.name}"的位置`);
        } catch (error) {
          console.warn(`处理景点"${spot.name}"失败:`, error.message);
          
          // 使用贵港市坐标作为备用
          if (index === 0) {
            ElMessage.warning(`无法获取景点"${spot.name}"的位置，使用贵港市中心坐标代替`);
            return {
              ...spot,
              lnglat: new AMap.LngLat(109.613196, 23.103333)
            };
          }
          return null;
        }
      })
    );
    
    if (!isComponentMounted) return;
    
    // 过滤掉没有找到位置的景点
    const validSpots = spotsWithLocation.filter(spot => spot !== null);
    console.log(`有效景点数量：${validSpots.length}/${sortedSpots.value.length}`);
    
    if (validSpots.length === 0) {
      ElMessage.error("无法获取任何景点的位置信息");
      isLoading.value = false;
      return;
    }
    
    if (!isComponentMounted) return;
    
    loadingMessage.value = '正在标记景点...';
    
    if (validSpots.length === 1) {
      // 只有一个景点，直接标记并定位到该景点
      const spot = validSpots[0];
      addMarker(spot, 1);
      safeMapOperation(() => {
        map.setCenter(spot.lnglat);
        map.setZoom(14);
      });
      
      routeInfo.value = {
        distance: "0米",
        duration: "0分钟"
      };
      
      // 标记完成后，关闭加载状态
      setTimeout(() => {
        isLoading.value = false;
        ElMessage.success("已标记景点位置");
      }, 500);
      
      return;
    }
    
    if (!isComponentMounted) return;
    
    // 在地图上标记所有景点
    validSpots.forEach((spot, index) => {
      if (isComponentMounted) {
        addMarker(spot, index + 1);
      }
    });
    
    if (!isComponentMounted) return;
    
    // 自动调整视图以包含所有标记
    safeMapOperation(() => map.setFitView());
    
    // 规划驾车路线
    loadingMessage.value = '正在规划驾车路线...';
    console.log("开始规划驾车路线");
    await planDrivingRoute(validSpots);
    
    // 所有步骤完成后，延迟一秒关闭加载状态，让用户看到完整地图
    setTimeout(() => {
      if (isComponentMounted) {
        isLoading.value = false;
      }
    }, 1000);
  } catch (error) {
    console.error("标记景点并规划路线失败:", error);
    if (isComponentMounted) {
      ElMessage.error("路线规划失败，请重试");
      isLoading.value = false;
    }
  }
};

// 在地图上添加标记
const addMarker = (spot, index) => {
  if (!isComponentMounted || !map) return;
  
  try {
    const marker = new AMap.Marker({
      position: spot.lnglat,
      title: spot.name,
      label: {
        content: `${index}. ${spot.name}`,
        direction: 'top'
      },
      icon: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_r' + (index < 10 ? index : 10) + '.png'
    });
    
    marker.on('click', () => {
      if (!isComponentMounted || !map) return;
      
      const infoWindow = new AMap.InfoWindow({
        content: `<div style="padding:10px;">
                    <h3 style="margin:0;color:#0D1326;font-size:16px;">${spot.name}</h3>
                    <p style="margin:10px 0 0;color:#666;">${spot.description || '暂无描述'}</p>
                  </div>`,
        offset: new AMap.Pixel(0, -30)
      });
      
      infoWindow.open(map, spot.lnglat);
    });
    
    if (map && isComponentMounted) {
      map.add(marker);
    }
  } catch (e) {
    console.error(`添加标记失败:`, e);
  }
};

// 搜索景点位置
const searchSpotLocation = (spotName) => {
  return new Promise((resolve, reject) => {
    if (!isComponentMounted) {
      reject(new Error("组件已卸载"));
      return;
    }
    
    if (!window.AMap) {
      reject(new Error("地图API未加载"));
      return;
    }
    
    // 不使用硬编码位置，始终通过搜索获取精确位置
    
    // 创建搜索实例
    if (!window.AMap.PlaceSearch) {
      // 尝试重新加载插件
      try {
        window.AMap.plugin('AMap.PlaceSearch');
        if (!window.AMap.PlaceSearch) {
          reject(new Error("PlaceSearch插件未加载"));
          return;
        }
      } catch (e) {
        reject(new Error("PlaceSearch插件加载失败"));
        return;
      }
    }
    
    try {
      const placeSearch = new AMap.PlaceSearch({
        city: '贵港',
        citylimit: true
      });
      
      // 为搜索添加城市名以提高准确性
      const searchKeyword = spotName.includes('贵港') ? spotName : `贵港${spotName}`;
      
      // 执行搜索
      placeSearch.search(searchKeyword, (status, result) => {
        if (!isComponentMounted) {
          reject(new Error("组件已卸载"));
          return;
        }
        
        if (status === 'complete' && result.poiList && result.poiList.pois && result.poiList.pois.length > 0) {
          const poi = result.poiList.pois[0];
          console.log(`搜索到景点"${spotName}"的精确位置：[${poi.location.lng}, ${poi.location.lat}]`);
          resolve([poi.location.lng, poi.location.lat]);
        } else {
          // 如果搜索失败，尝试使用更多关键词组合
          const extendedKeywords = [
            `广西贵港 ${spotName}`,
            `贵港市 ${spotName}`,
            spotName.replace(/贵港/, '')
          ];
          
          // 递归尝试不同的关键词
          const tryNextKeyword = (index) => {
            if (index >= extendedKeywords.length) {
              reject(new Error(`未找到景点"${spotName}"的位置`));
              return;
            }
            
            const keyword = extendedKeywords[index];
            console.log(`尝试使用扩展关键词搜索：${keyword}`);
            
            placeSearch.search(keyword, (status, result) => {
              if (status === 'complete' && result.poiList && result.poiList.pois && result.poiList.pois.length > 0) {
                const poi = result.poiList.pois[0];
                console.log(`通过扩展关键词找到景点位置：[${poi.location.lng}, ${poi.location.lat}]`);
                resolve([poi.location.lng, poi.location.lat]);
              } else {
                // 尝试下一个关键词
                tryNextKeyword(index + 1);
              }
            });
          };
          
          tryNextKeyword(0);
        }
      });
    } catch (e) {
      reject(new Error(`搜索执行错误: ${e.message}`));
    }
  });
};

// 规划驾车路线
const planDrivingRoute = (spots) => {
  return new Promise((resolve, reject) => {
    if (!isComponentMounted) {
      reject(new Error("组件已卸载"));
      return;
    }
    
    if (!map || !mapIsReady.value) {
      reject(new Error("地图未准备好，无法规划路线"));
      return;
    }
    
    if (!window.AMap) {
      reject(new Error("AMap未加载，无法规划路线"));
      return;
    }
    
    try {
      // 确保有驾车规划插件
      if (!window.AMap.Driving) {
        try {
          window.AMap.plugin('AMap.Driving');
          if (!window.AMap.Driving) {
            if (isComponentMounted) {
              ElMessage.error("导航插件加载失败");
            }
            reject(new Error("导航插件加载失败"));
            return;
          }
        } catch (e) {
          if (isComponentMounted) {
            ElMessage.error("导航插件加载失败");
          }
          reject(new Error("导航插件加载失败: " + e.message));
          return;
        }
      }
      
      if (!isComponentMounted) {
        reject(new Error("组件已卸载"));
        return;
      }
      
      try {
        // 创建驾车规划实例
        const driving = new AMap.Driving({
          map: map,
          panel: null, // 不使用路径规划面板
          policy: AMap.DrivingPolicy.LEAST_TIME, // 最快捷模式
          autoFitView: true // 自动调整地图视野以包含所有路线
        });
        
        // 起点为第一个景点
        const start = spots[0].lnglat;
        // 终点为最后一个景点
        const end = spots[spots.length - 1].lnglat;
        // 途经点为中间的景点
        const waypoints = spots.slice(1, -1).map(spot => spot.lnglat);
        
        console.log(`规划路线：起点=${spots[0].name}, 终点=${spots[spots.length-1].name}, 途经点=${waypoints.length}个`);
        
        // 设置超时保护
        const timeoutId = setTimeout(() => {
          if (isComponentMounted) {
            console.warn("路线规划超时，使用默认路线信息");
            routeInfo.value = {
              distance: "计算中...",
              duration: "计算中..."
            };
            resolve(); // 即使超时也要解析promise以继续流程
          }
        }, 8000); // 8秒超时
        
        // 开始规划
        driving.search(
          start, 
          end, 
          { waypoints: waypoints },
          (status, result) => {
            clearTimeout(timeoutId);
            
            // 检查组件是否已卸载
            if (!isComponentMounted) {
              reject(new Error("组件已卸载"));
              return;
            }
            
            if (status === 'complete' && result && result.routes && result.routes.length > 0) {
              console.log("路线规划成功", result);
              
              try {
                const route = result.routes[0];
                
                // 更新路线信息
                if (isComponentMounted) {
                  routeInfo.value = {
                    distance: formatDistance(route.distance),
                    duration: formatDuration(route.time)
                  };
                  
                  ElMessage.success("路线规划成功");
                  resolve();
                }
              } catch (e) {
                console.error("处理路线规划结果出错:", e);
                
                if (isComponentMounted) {
                  routeInfo.value = {
                    distance: "计算中...",
                    duration: "计算中..."
                  };
                  resolve(); // 仍然解析promise以继续流程
                }
              }
            } else {
              console.error("路线规划失败:", result);
              
              if (isComponentMounted) {
                ElMessage.error("路线规划失败，请重试");
                
                // 设置一个默认的路线信息
                routeInfo.value = {
                  distance: "计算中...",
                  duration: "计算中..."
                };
                resolve(); // 仍然解析promise以继续流程
              }
            }
          }
        );
      } catch (error) {
        console.error("驾车路线规划执行错误:", error);
        
        if (isComponentMounted) {
          ElMessage.error("路线规划出错");
          
          // 设置一个默认的路线信息
          routeInfo.value = {
            distance: "未知",
            duration: "未知"
          };
          resolve(); // 仍然解析promise以继续流程
        }
      }
    } catch (error) {
      console.error("总体驾车路线规划错误:", error);
      
      if (isComponentMounted) {
        ElMessage.error("路线规划功能错误");
        
        // 设置一个默认的路线信息
        routeInfo.value = {
          distance: "未知",
          duration: "未知"
        };
        reject(error);
      }
    }
  });
};

// 格式化距离
const formatDistance = (meters) => {
  if (!meters || isNaN(meters)) return "未知距离";
  
  if (meters >= 1000) {
    return `${(meters / 1000).toFixed(1)}公里`;
  }
  return `${Math.round(meters)}米`;
};

// 格式化时间
const formatDuration = (seconds) => {
  if (!seconds || isNaN(seconds)) return "未知时间";
  
  if (seconds >= 3600) {
    const hours = Math.floor(seconds / 3600);
    const minutes = Math.floor((seconds % 3600) / 60);
    return `${hours}小时${minutes > 0 ? minutes + '分钟' : ''}`;
  } else if (seconds >= 60) {
    const minutes = Math.floor(seconds / 60);
    return `${minutes}分钟`;
  }
  return `${Math.round(seconds)}秒`;
};

// 分享路线
const handleShare = () => {
  if (isComponentMounted) {
  ElMessage.success("分享功能开发中");
  }
};

// 保存路线
const handleSave = () => {
  if (!isComponentMounted) return;
  
  if (!mapIsReady.value) {
    ElMessage.warning("路线尚未规划完成");
    return;
  }
  
  // 如果没有路线信息，创建一个默认的
  if (!routeInfo.value) {
    routeInfo.value = {
      distance: "未知",
      duration: "未知"
    };
  }

  emit("save", {
    spots: sortedSpots.value, // 使用排序后的景点列表
    routeInfo: routeInfo.value
  });
  
  ElMessage.success("路线已保存");
  dialogVisible.value = false;
};

// 关闭对话框
const handleClose = () => {
  console.log("关闭路线规划对话框");
  
  safeMapOperation(() => map.clearMap());
  
  // 重置状态但不销毁地图
  mapIsReady.value = false;
  routeInfo.value = null;
  // 重要：关闭时也要重置初始化标志，以便下次打开时重新初始化
  isMapInitialized.value = false;
  isLoading.value = true;
};

// 监听对话框显示状态
watch(() => props.modelValue, (val) => {
  if (!isComponentMounted) return;
  
  if (val) {
    // 对话框显示时，会触发handleDialogOpened来初始化地图
    console.log("对话框显示状态发生变化:", val);
    // 重置状态
    mapIsReady.value = false;
    routeInfo.value = null;
    // 确保每次打开对话框时重置初始化标志
    isMapInitialized.value = false;
    // 设置加载状态
    isLoading.value = true;
    loadingMessage.value = '正在初始化地图...';
  }
});

// 确保在组件卸载前清理所有资源
onBeforeUnmount(() => {
  cleanup();
});

// 使用onUnmounted作为备份清理机制
onUnmounted(() => {
  cleanup();
});

// 清理资源的方法
const cleanup = () => {
  console.log("组件卸载，销毁地图实例");
  isComponentMounted = false;
  
  if (map) {
    try {
      map.clearMap();
      map.destroy();
    } catch(e) {
      console.warn("销毁地图实例失败:", e);
    }
    map = null;
  }
  
  // 重置所有状态
  mapIsReady.value = false;
  isMapInitialized.value = false;
  routeInfo.value = null;
};

// 计算两点之间的距离
const calculateDistance = (point1, point2) => {
  if (!point1 || !point2) return 0;
  
  // 使用简化版的球面余弦定律计算两点间距离
  const R = 6371; // 地球半径，单位是千米
  const lat1 = point1[1] * Math.PI / 180;
  const lat2 = point2[1] * Math.PI / 180;
  const lon1 = point1[0] * Math.PI / 180;
  const lon2 = point2[0] * Math.PI / 180;
  
  const dLat = lat2 - lat1;
  const dLon = lon2 - lon1;
  
  const a = Math.sin(dLat/2) * Math.sin(dLat/2) +
            Math.cos(lat1) * Math.cos(lat2) * 
            Math.sin(dLon/2) * Math.sin(dLon/2);
  const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
  const distance = R * c;
  
  return distance;
};

// AI智能规划路线
const aiPlanRoute = async () => {
  if (props.spots.length < 3) {
    ElMessage.warning('至少需要3个景点才能进行AI智能规划');
    return;
  }
  
  // 显示加载状态
  isLoading.value = true;
  loadingMessage.value = '正在使用AI智能算法规划最优路线...';
  
  ElMessage.info('正在使用AI智能算法规划最优路线...');
  
  try {
    // 1. 首先获取所有景点的坐标信息
    const spotsWithCoordinates = await Promise.all(
      props.spots.map(async (spot) => {
        // 如果已有坐标
        if (spot.longitude && spot.latitude && 
            !isNaN(spot.longitude) && !isNaN(spot.latitude)) {
          return {
            ...spot,
            coordinates: [spot.longitude, spot.latitude]
          };
        }
        
        // 通过搜索获取坐标
        try {
          const location = await searchSpotLocation(spot.name);
          if (location) {
            return {
              ...spot,
              coordinates: location
            };
          }
        } catch (e) {
          console.warn(`无法获取景点"${spot.name}"的坐标`);
        }
        
        // 如果无法获取坐标，使用贵港市中心坐标
        ElMessage.warning(`无法获取景点"${spot.name}"的坐标，使用贵港市中心坐标代替`);
        return {
          ...spot,
          coordinates: [109.613196, 23.103333]
        };
      })
    );
    
    // 2. 计算所有景点对之间的距离矩阵
    const distanceMatrix = [];
    for (let i = 0; i < spotsWithCoordinates.length; i++) {
      distanceMatrix[i] = [];
      for (let j = 0; j < spotsWithCoordinates.length; j++) {
        const distance = calculateDistance(
          spotsWithCoordinates[i].coordinates,
          spotsWithCoordinates[j].coordinates
        );
        distanceMatrix[i][j] = distance;
      }
    }
    
    // 3. 找出距离最远的两个点作为起点和终点
    let maxDistance = 0;
    let startIndex = 0;
    let endIndex = 0;
    
    for (let i = 0; i < distanceMatrix.length; i++) {
      for (let j = i + 1; j < distanceMatrix.length; j++) {
        if (distanceMatrix[i][j] > maxDistance) {
          maxDistance = distanceMatrix[i][j];
          startIndex = i;
          endIndex = j;
        }
      }
    }
    
    // 4. 确定起点和终点
    const startSpot = spotsWithCoordinates[startIndex];
    const endSpot = spotsWithCoordinates[endIndex];
    
    // 5. 收集需要排序的途经点
    const waypoints = spotsWithCoordinates.filter((_, index) => 
      index !== startIndex && index !== endIndex
    );
    
    // 6. 根据与起点的距离对途经点进行排序（贪心算法）
    let currentPoint = startSpot.coordinates;
    const sortedWaypoints = [];
    
    // 复制一份途经点数组，我们将从中选择最近的点
    const remainingWaypoints = [...waypoints];
    
    // 当还有剩余途经点时，继续选择
    while (remainingWaypoints.length > 0) {
      // 找出距离当前点最近的下一个点
      let minDistance = Infinity;
      let nextPointIndex = -1;
      
      for (let i = 0; i < remainingWaypoints.length; i++) {
        const distance = calculateDistance(
          currentPoint,
          remainingWaypoints[i].coordinates
        );
        
        if (distance < minDistance) {
          minDistance = distance;
          nextPointIndex = i;
        }
      }
      
      // 将最近的点添加到排序后的数组中
      const nextPoint = remainingWaypoints[nextPointIndex];
      sortedWaypoints.push(nextPoint);
      
      // 更新当前点
      currentPoint = nextPoint.coordinates;
      
      // 从剩余点中移除已选择的点
      remainingWaypoints.splice(nextPointIndex, 1);
    }
    
    // 7. 组合最终的路线顺序：起点 + 排序后的途经点 + 终点
    const optimizedRoute = [startSpot, ...sortedWaypoints, endSpot];
    
    // 8. 更新sortedSpots并重新规划路线
    sortedSpots.value = optimizedRoute;
    
    ElMessage.success('AI智能规划完成，已找到最优路线！');
    
    // 如果地图已加载，重新规划路线
    if (mapIsReady.value) {
      // 不调用replanRoute()而是直接调用markSpotsAndPlanRoute()
      // 因为replanRoute()会再次设置isLoading
      markSpotsAndPlanRoute();
    } else {
      isLoading.value = false;
    }
  } catch (error) {
    console.error('AI智能规划路线失败:', error);
    ElMessage.error('智能规划失败，请重试');
    isLoading.value = false;
  }
};
</script>

<style lang="scss" scoped>
.route-dialog {
  :deep(.el-dialog__body) {
    padding: 24px;
  }
}

.route-planner {
  position: relative;
  transition: opacity 0.3s ease;
}

.map-container {
  height: 450px;
  width: 100%;
  position: relative;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  margin-bottom: 16px;
}

#route-map-container {
  height: 100%;
  width: 100%;
}

.route-control-panel {
  border-radius: 8px;
  
  .spot-list-draggable {
    max-height: 200px;
    overflow-y: auto;
  }
  
  .spot-item {
    transition: background-color 0.2s;
    padding: 8px;
    border-radius: 4px;
    
    &:hover {
      background-color: #f9f9f9;
    }
  }
  
  .drag-handle {
    cursor: move;
  }
}

.full-screen-loading {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(255, 255, 255, 0.9);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 100;
  border-radius: 8px;
  
  .loading-content {
    text-align: center;
    padding: 30px;
    background-color: white;
    border-radius: 12px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
    max-width: 90%;
    animation: fadeIn 0.3s ease;
  }
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.map-loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(255, 255, 255, 0.8);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 10;
  
  .loading-content {
    text-align: center;
    padding: 20px;
    background-color: white;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  }
}

.route-info {
  position: absolute;
  top: 20px;
  right: 20px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  padding: 15px;
  min-width: 200px;
  z-index: 5;
  
  .info-header {
    margin-bottom: 10px;
    border-bottom: 1px solid #eee;
    padding-bottom: 5px;
    
    h3 {
      margin: 0;
      font-size: 16px;
    }
  }
  
  .info-content {
    .info-item {
      margin-bottom: 8px;
      
      .info-label {
        color: #666;
        margin-right: 5px;
      }
      
      .info-value {
        font-weight: 500;
      }
    }
  }
}

.smart-plan-btn {
  background-color: #42b983;
  border-color: #42b983;
  
  &:hover {
    background-color: #36a478;
    border-color: #36a478;
  }
  
  &:disabled {
    background-color: #a8e2c9;
    border-color: #a8e2c9;
  }
}
</style>
